<?
class Bmail{


	private $conf = null;
	public function __construct($conf){
		$this->conf = $conf;
	}
	/**
	 * <p>以SMTP的方式发送邮件</p>
	 * 
	 * @return true,false - 是否成功发送bool
	 * @param $mailcfg array - 邮件发送的配置
	 * @param $mail array - 邮件的内容
	 */

    public function send($mail){
    	$mailcfg = $this->conf;
        //无法连接上smtp服务器
        if(!$fp = fsockopen($mailcfg['server'], $mailcfg['port'], $errno, $errstr, 50)) {
            //echo ('无法连接');
            throw new PException("无法链接");
        }
        stream_set_blocking($fp, true);
        $lastmessage = fgets($fp, 512);
        if(substr($lastmessage, 0, 3) != '220') {
            $error_msg = "$mailcfg[server]:$mailcfg[port] CONNECT - $lastmessage";
            //echo ('连接错误');
            throw new PException("连接错误");
        }
        //发送用户名
        fputs($fp, ($mailcfg['auth'] ? 'EHLO' : 'HELO')." ".$mailcfg['auth_username']."\r\n");
        $lastmessage = fgets($fp, 512);
        if(substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250) {
            
            $error_msg = "($mailcfg[server]:$mailcfg[port]) HELO/EHLO - $lastmessage";
            //echo ('身份错误');
            throw new PException("账号认证错误");
        }
        while(1) {
            if(substr($lastmessage, 3, 1) != '-' || empty($lastmessage)) {break;}
            $lastmessage = fgets($fp, 512);
        }
        //登录验证
        if($mailcfg['auth']) {
            fputs($fp, "AUTH LOGIN\r\n");
            $lastmessage = fgets($fp, 512);
            if(substr($lastmessage, 0, 3) != 334) {
                //登陆模式错误
                $error_msg = "($mailcfg[server]:$mailcfg[port]) AUTH LOGIN - $lastmessage";
                //echo ('登录模式错误');
                throw new PException("登录模式错误");
            }
            fputs($fp, base64_encode($mailcfg['auth_username'])."\r\n");
            $lastmessage = fgets($fp, 512);
            if(substr($lastmessage, 0, 3) != 334) {
                //用户名不正确
                $error_msg = "($mailcfg[server]:$mailcfg[port]) USERNAME - $lastmessage";
                //echo ('用户名不正确');
                throw new PException("用户名错误");
            }
            fputs($fp, base64_encode($mailcfg['auth_password'])."\r\n");
            $lastmessage = fgets($fp, 512);
            if(substr($lastmessage, 0, 3) != 235) {
                //用户密码不正确
                $error_msg = "($mailcfg[server]:$mailcfg[port]) PASSWORD - $lastmessage";
                //echo ('用户密码不正确');
                throw new PException("密码错误");
            }
            
            $email_from = $mailcfg['from'];
        }
        fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
        $lastmessage = fgets($fp, 512);
        if(substr($lastmessage, 0, 3) != 250) {
            //发送地址错误
            $error_msg = "($mailcfg[server]:$mailcfg[port]) MAIL FROM - $lastmessage";
            //echo ('发送地址错误');
            throw new PException("发送地址错误");
        }
    
        $email_to=$mail['to'];
        //循环对逐个收件人发送
        foreach(explode(',', $email_to) as $touser) {
            $touser = trim($touser);
            if($touser) {
                fputs($fp, "RCPT TO: <$touser>\r\n");
                $lastmessage = fgets($fp, 512);
                if(substr($lastmessage, 0, 3) != 250) {
                    //目标地址错误
                    $error_msg = "($mailcfg[server]:$mailcfg[port]) RCPT TO - $lastmessage";
                    //echo ('目标地址错误');
                    throw new PException("目标地址错误");
                }
            }
        }
        fputs($fp, "DATA\r\n");
        $lastmessage = fgets($fp, 512);
        if(substr($lastmessage, 0, 3) != 354) {
            $error_msg = "($mailcfg[server]:$mailcfg[port]) DATA - $lastmessage";
            //echo ('数据错误');
            throw new PException("数据错误".$error_msg);
        }
    
        $from = $mailcfg['from'];
        $fromname = $mailcfg['fromname'];
        $subject = $mail['subject'];
        $content = $mail['content'];
        
        $charset = $mailcfg['charset'];
        $headers = "MIME-Version: 1.0\r\nContent-type: $mailcfg[type]; charset=".$charset."\r\n\r\n";//头文件避免出现乱码
        
        //构建邮件数据
        $str="To: $email_to\r\nFrom: $fromname <$from>\r\nSubject: ".$subject."\r\n".$headers.$content."\r\n.\r\n";
        fputs($fp, "$str\r\n");
        fputs($fp, "QUIT\r\n");     
        return true;
    }

}

/********
//以下为调用例子
define("REG_SMTP_HOST",			"smtp.163.com");//如果是ssl类型的smtp，改成'ssl://smtp.163.com' 即可
define("REG_SMTP_USER",			"testuser");
define("REG_SMTP_PASS",			"mima");
define("REG_SMTP_FROM",			"m2@sohu.com");

require_once('b-mail.php');

$mailcfg = array(
              'server'=>REG_SMTP_HOST,
              'port'=>'25',//smtp服务器端口
              'auth'=>1,
              'from'=>REG_SMTP_FROM,
              'charset'=>'utf-8',//信件编码
              'type'=>'text/html',//发送的类型是html格式
              //'type'=>'text/plain',//发送的类型是文本格式
              'fromname'=>'内容监控平台(M2)',
              'auth_username'=>REG_SMTP_USER,
              'auth_password'=>REG_SMTP_PASS);
              

$mail = array(
           'to'=>'test@hotmail.com',
           'subject'=>'test',
           'content'=>'test content');
                  
$rst = BMail::send($mailcfg,$mail);
if(!$rst){
    echo 'mail fail';
}else{
    echo 'mail succ';
}
**********/


?>